function kagi(x)
%KAGI Kagi chart.
%   KAGI(X) plots the stock data in a Kagi chart.  X is an Mx2
%   matrix where the first column contains date numbers and the second
%   column is the asset price.    
%
%   See also BOLLING, CANDLE, HIGHLOW, LINEBREAK, MOVAVG, POINTFIG, RENKO, VOLAREA, PRICEANDVOL.

%	Copyright 1995-2007 The MathWorks, Inc.
%	$Revision: 1.1.6.2 $   $Date: 2007/11/22 16:39:58 $

%Counter used to visually buckets of data
kcount = 1;

%Preallocate kagi data and linewidth settings
numpoints = size(x,1);
d = NaN(numpoints*2,2);
linewidth = ones(numpoints*2,1);

%Initialize buy and sell levels
buylevel = zeros(numpoints*2,1);
selllevel = buylevel;

%Build data set

%Set first two data points
d(1,1) = 1;
d(1,2) = x(1,2);
d(2,1) = 1;
d(2,2) = x(2,2);

%Set starting dates
dates(1) = x(1,1);

%Get trend and set initial linewidth flag, buy and sell levels
s = sign(x(2,2) - x(1,2));
if s > 0
  linewidth(2) = true;
  selllevel(2) = x(1,2);
elseif s < 0
  buylevel(2) = x(1,2);
end

%Fill in remainder of data based in sign changes
j = 3;
for i = 3:numpoints
  news = sign(x(i,2) - x(i-1,2));
  if news ~= s 
    kcount = kcount + 1;
    d(j,1) = kcount;
    d(j,2) = x(i-1,2);
    j = j+1;
    d(j,1) = kcount;
    d(j,2) = x(i,2);
    j = j + 1;
    dates(kcount) = x(i,1);
  else
    d(j,1) = kcount;
    d(j,2) = x(i,2);
    j = j + 1;
  end
  s = news;
end

%Remove NaN's
d(isnan(d(:,1)),:) = [];

%Create data vector that denotes when security should be purchased and held
thickdata = d;   

%Determine buy levels, sell levels, holding state and linewidths
for i = 3:size(d,1)
  if (d(i-1,1) < d(i,1)) && (d(i-2,2) < d(i-1,2))
    buylevel(i) = d(i,2);
    selllevel(i) = selllevel(i-1);
  elseif (d(i-1,1) < d(i,1)) && (d(i-2,2) > d(i-1,2))
    selllevel(i) = d(i,2);
    buylevel(i) = buylevel(i-1);
  else
    selllevel(i) = selllevel(i-1);
    buylevel(i) = buylevel(i-1);
  end
end  

%Set initial buy and sell levels
k = find(selllevel > 0);
selllevel(1:k(1)-1) = selllevel(k(1));
k = find(buylevel > 0);
buylevel(1:k(1)-1) = buylevel(k(1));

%Set linewidth flags for use with thick data settings
for i = 3:size(d,1)
  if d(i,2) < selllevel(i)
    linewidth(i) = true;
  elseif d(i,2) > buylevel(i)
    linewidth(i) = false;
  else
    linewidth(i) = linewidth(i-1);
  end
end
  
%NaN out thickdata values where line shouldn't be displayed
for i = 1:size(thickdata,1)
  if linewidth(i) 
    thickdata(i,2) = NaN;
  end
end
    
%Display data
figure;hold on
plot(d(:,1),d(:,2))
plot(thickdata(:,1),thickdata(:,2),'linewidth',2)
hold off
xticks = unique(round(get(gca,'Xtick')));
datelabels = datestr(dates(xticks(2:end-1)));
set(gca,'xlim',[0 max(d(:,1))+1],'xticklabel',[],...
   'xtick',xticks(2:end-1),'xticklabel',datelabels,'Tag','kagichart',...
   'xgrid','on','ygrid','on','box','on','YAxisLocation','right')

      


